import log from '../../../helpers/logger';
import { pushDiscordWebhook } from '../../../helpers/pushDiscordWebhook';
//import { validateLink } from '../../../helpers/dataValidation';

import {
  authorizedRouteHandler,
  ControllerMethodTypes,
  defaultRouteHandler,
} from '../../../../interfaces';
import { Request, Response } from 'hyper-express';
import { showSelectedObjectKeys } from '../../../helpers/utilsJS';
import { wechatopen_applet } from '../../../../../prisma/generated/uctoo';
import { setExCache } from '../../../helpers/redis';
import { OfficialAccount, ServerRequest, FormData, defineOfficialAccountConfig } from 'node-easywechat';
import Message from 'node-easywechat';
  //#region AutoCreateCode
import {
  createWechatopenApplet,
  deleteWechatopenAppletFromDatabase,
  deleteMultiWechatopenAppletFromDatabase,
  editWechatopenAppletInDatabase,
  editMultiWechatopenAppletInDatabase,
  getWechatopenAppletFromDatabase,
  getWechatopenAppletsFromDatabase,
  queryWechatopenAppletsFromDatabase,
  countWechatopenApplets
} from '../../../services/uctoo/wechatopen_applet';

class uctooWechatopenAppletController {

  protected validateAndDestructureBody = async (
    req: Request,
    userId: string,
    actionType: ControllerMethodTypes
  ) => {
    const body = await req.json();
    const keysArray = Object.keys(body);       //如需自定义控制接收字段可在此定义，如['id','link','privacy_level','owner','description','group_id','stars'] ，默认接收所有提交字段
    const uctooWechatopenApplet = showSelectedObjectKeys(body, keysArray) as wechatopen_applet;
    uctooWechatopenApplet.creator = userId;

    return uctooWechatopenApplet;
  };
  public add: authorizedRouteHandler = async (req, res) => {
    try {
      const user = res.locals.id.user;
      const uctooWechatopenApplet = await this.validateAndDestructureBody(
        req,
        user,
        ControllerMethodTypes.ADD
      );
      if (!uctooWechatopenApplet) return res.status(400).json({ errno: "40001", errmsg: '提交数据格式错误' });

      const createdWechatopenApplet = await createWechatopenApplet(uctooWechatopenApplet);
      if (!createdWechatopenApplet) return res.status(500).json({ errno: "50001", errmsg: "database query failed" });

      res.status(200).json(createdWechatopenApplet);
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public edit: authorizedRouteHandler = async (req, res) => {
    try {
      const user = res.locals.id.user;
      const body = await req.json();
      const { id,ids,force } = body;

      if(ids){
        const uctooWechatopenApplet = await this.validateAndDestructureBody(
          req,
          user,
          ControllerMethodTypes.EDIT
        );
        if (!uctooWechatopenApplet) return res.status(400).json({ errno: "40001", errmsg: '提交数据格式错误' });

        const editedWechatopenApplet = await editMultiWechatopenAppletInDatabase(uctooWechatopenApplet, JSON.parse(ids), user);
        
        if (typeof editedWechatopenApplet === 'object' && 'success' in editedWechatopenApplet) {
          if (!editedWechatopenApplet.success) {
            return res.status(403).json({
              errno: "40301", 
              errmsg: editedWechatopenApplet.reason,
              ...(editedWechatopenApplet.wechatopenAppletId && { wechatopenAppletId: editedWechatopenApplet.wechatopenAppletId })
            });
          }
          return res.status(200).json(editedWechatopenApplet.data);
        }
        
        res.status(200).json(editedWechatopenApplet);
      }else{
        const uctooWechatopenApplet = await this.validateAndDestructureBody(
          req,
          user,
          ControllerMethodTypes.EDIT
        );
        if (!uctooWechatopenApplet) return res.status(400).json({ errno: "40001", errmsg: '提交数据格式错误' });

        const editedWechatopenApplet = await editWechatopenAppletInDatabase(uctooWechatopenApplet, uctooWechatopenApplet.id, user);
        
        if (typeof editedWechatopenApplet === 'object' && 'success' in editedWechatopenApplet) {
          if (!editedWechatopenApplet.success) {
            return res.status(403).json({ errno: "40301", errmsg: editedWechatopenApplet.reason });
          }
          return res.status(200).json(editedWechatopenApplet.data);
        }
        res.status(200).json(editedWechatopenApplet);
      }      
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public delete: authorizedRouteHandler = async (req, res) => {
    try {
      const body = await req.json();
      const { id,ids,force } = body;
      const user = res.locals.id.user;

      if(ids){
        const deletionResult = await deleteMultiWechatopenAppletFromDatabase(JSON.parse(ids), force, user);
        
        if (typeof deletionResult === 'object' && 'success' in deletionResult) {
          if (!deletionResult.success) {
            return res.status(403).json({
              errno: "40301", 
              errmsg: deletionResult.reason,
              ...(deletionResult.wechatopenAppletId && { wechatopenAppletId: deletionResult.wechatopenAppletId })
            });
          }
          return res.status(200).json({ desc: '删除成功' });
        }
        
      }else{
        const deletionResult = await deleteWechatopenAppletFromDatabase(id, force, user);
        
        if (typeof deletionResult === 'object' && 'success' in deletionResult) {
          if (!deletionResult.success) {
            return res.status(403).json({ errno: "40301", errmsg: deletionResult.reason });
          }
          return res.status(200).json({ desc: '删除成功' });
        }
        
      }

      res.status(200).json({ desc: '删除成功' });
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public getSingle: authorizedRouteHandler = async (req, res) => {
    try {
      const { id } = req.params;
      const user = res.locals.id.user;

      const wechatopenAppletFromDb = await getWechatopenAppletFromDatabase(id, user);
      if (!wechatopenAppletFromDb) {
        return res.status(404).json({ 
          errno: "40401", 
          errmsg: '未找到该实体或您没有权限访问' 
        });
      }

      res.status(200).json(wechatopenAppletFromDb);
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public getMany: authorizedRouteHandler = async (req, res) => {
    try {
      const limit = parseInt(req.params.limit);
      const page = parseInt(req.params.page) || 0;
      const skip = parseInt(req.params.skip) || 0;
      const query = req.query;
      
      if (limit > 100) return res.status(400).json({ errno: "40002", errmsg: '请求数量不能超过100条' });
      if (isNaN(limit)) return res.status(400).json({ errno: "40003", errmsg: '请求数量必须是数字' });
      
      const user = res.locals.id.user;
      const totalCount = await countWechatopenApplets(user);
      
      if (query) {
        const wechatopenAppletsFromDb = await queryWechatopenAppletsFromDatabase(limit, page, skip, query, user);
        if (!wechatopenAppletsFromDb) return res.status(404).json({ errno: "40401", errmsg: '未找到符合条件的实体' });

        res.status(200).json({
          currentPage: page,
          totalCount: totalCount,
          totalPage: Math.ceil(Number(totalCount)/limit),
          wechatopenApplets: wechatopenAppletsFromDb
        });
      } else {
        const wechatopenAppletsFromDb = await getWechatopenAppletsFromDatabase(limit, skip, page, user);
        if (!wechatopenAppletsFromDb) return res.status(404).json({ errno: "40401", errmsg: '未找到符合条件的实体' });

        res.status(200).json({
          currentPage: page,
          totalCount:totalCount,
          totalPage: Math.ceil(Number(totalCount)/limit),
          wechatopenApplets: wechatopenAppletsFromDb
        });
      }


    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  //#endregion AutoCreateCode

  public officialAccountServer: defaultRouteHandler = async (req, res) => {


    try {

      const oa = defineOfficialAccountConfig({
        // 微信公众号的 app key
        app_id: '',
        // 微信公众号的 app secret
        secret: '',
        // 微信公众号的 token
        token: 'uctoo',
        // EncodingAESKey
        aes_key: 'uxo7tdM2iF5PQiQSLNfpdDD4k4X6ajVYJxEIxtxDYLg',

        // 网页授权认证
        oauth: {
          // 网页授权类型
          scope: 'snsapi_userinfo',
          // 网页授权回调地址，完整的URL
          redirect_url: 'https://demoapi.uctoo.com/wxlogin/callback'
        },
      })
      const wxapp = new OfficialAccount(oa);
      const body = await req.text();

      const request = new ServerRequest(
        req.method,
        req.url,
        req.headers,
        body,
        '1.1',
        req.query_parameters
      );
      wxapp.setRequest(request);

      const wxserver = wxapp.getServer();

      wxserver.with(async (message) => {
        //  console.log('message', message);
        return;

      });

      const response = await wxserver.serve();

      // console.log('response', response);
      res.type('application/octet-stream'); //Connection application/octet-stream
      res.header('Connection', 'keep-alive'); //Keep-Alive	timeout=5
      res.header('Keep-Alive', 'timeout=5');
      res.removeHeader['access-control-allow-origin'];
      res.removeHeader['access-control-allow-credentials'];
      //res.attachment()
      res.send(response.getBody());

    } catch (e) {
      log.error({ err: e.message, desc: e });
      return res.status(500).json({ err: e.message, desc: e });
    }

  }

}

export default uctooWechatopenAppletController;
